package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import dao.DormitoryDao;
import dao.DormroomsDao;
import dao.impl.DormitoryDaoImpl;
import dao.impl.DormroomsDaoImpl;
import entity.Dormitory;
import entity.Dormrooms;
import service.DormitoryService;
import service.DormroomsService;
import service.impl.DormitoryServiceImpl;
import service.impl.DormroomsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/DormroomsController")
public class DormroomsController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        if (op.equals("cxb")) {
            String lid = req.getParameter("lid");
            String pageStr = req.getParameter("page");
            int page = StringUtils.isNullOrEmpty(pageStr) ? 0 : Integer.parseInt(pageStr);
            int pageSize = 5; // 每页5条记录
            DormroomsDao dsd = new DormroomsDaoImpl();
            List<Dormrooms> list = null;
            int totalCount = 0;
            try {
                Integer lidParam = StringUtils.isNullOrEmpty(lid) ? null : Integer.valueOf(lid);
                totalCount = dsd.getTotalCount(lidParam);
                int totalPages = (totalCount + pageSize - 1) / pageSize;
                page = Math.max(0, Math.min(page, totalPages - 1));
                list = dsd.cxb(lidParam, page, pageSize);
                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);

                out.write(JSON.toJSONString(result));
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (op.equals("scb")) {
            DormroomsDao dsd = new DormroomsDaoImpl();
            try {
                String dormId = req.getParameter("id");
                if (dormId != null && !dormId.isEmpty()) {
                    int isSuccess = dsd.scb(Integer.parseInt(dormId));

                    // 添加删除结果响应
                    if (isSuccess > 0) {
                        out.write("删除成功");
                    } else {
                        out.write("删除失败，记录不存在");
                    }

                    List<Dormrooms> list = dsd.cx2(0);
                    session.setAttribute("list", list);
                } else {
                    out.write("宿舍ID不能为空");
                }
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("删除失败：" + e.getMessage());
            }
        } else if (op.equals("update2")) {
            // 接收前端发送的参数
            String roomId = req.getParameter("roomId");
            String buildingId = req.getParameter("buildingId");
            String roomNumber = req.getParameter("roomNumber");
            String floor = req.getParameter("floor");
            String capacity = req.getParameter("capacity");

            DormroomsDao dsd = new DormroomsDaoImpl();
            try {
                // 调用修改方法，使用roomId作为条件更新宿舍信息
                int success = dsd.xgb(
                        Integer.parseInt(roomId),
                        Integer.parseInt(buildingId),
                        roomNumber,
                        Integer.parseInt(floor),
                        Integer.parseInt(capacity)
                );
                if (success > 0) {
                    out.write("修改成功");
                } else {
                    out.write("修改失败，记录不存在");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                out.write("修改失败，数据库错误");
            } catch (NumberFormatException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("修改失败，参数格式错误");
            }
        }else if (op.equals("add2")){
            String buildingId=req.getParameter("buildingId");
            String roomNumber=req.getParameter("roomNumber");
            String floor=req.getParameter("floor");
            String capacity=req.getParameter("capacity");

            if(buildingId ==null||buildingId.isEmpty()|| roomNumber == null|| roomNumber.isEmpty() || floor==null|| floor.isEmpty()|| capacity ==null||capacity.isEmpty()){
               out.write("所有字段不能为空");
               return;
            }
            DormroomsService dsd=new DormroomsServiceImpl();
                try {
                    dsd.tjb(Integer.parseInt(buildingId), roomNumber, Integer.parseInt(floor), Integer.parseInt(capacity));
                    out.write("添加成功");
                } catch (SQLException e) {
                    e.printStackTrace();
                    out.write("添加失败" + e.getMessage());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    out.write("添加失败" + e.getMessage());
                } catch (NumberFormatException e) {
                    out.write("参数格式错误");
                }


        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
